package com.heima.user.service.Impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.article.pojos.ApUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.treadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //参数校验
        //是否登入
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //operation的值 必须是0或1
        Short operation = dto.getOperation();
        if(operation.intValue() !=0 && operation.intValue() !=1){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"关注方式错误");
        }

        //是否已经关注zscore
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        //参数1 在集合中找key  参数2 要找的元素 返回值 如果有这个歌元素返回score 如果没有返回null

        //判断operation的值是否等于0
        if(operation.intValue() == 0){
            //自己不能关注自己
            if(user.getId() == dto.getAuthorApUserId()){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"自己不能关注自己");
            }

            Double score = zSetOperations.score(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(dto.getAuthorApUserId()));
            if(score != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"你已经关注过该作者");
            }

            //如果是0 关注该作者 zadd 集合添加数据
            zSetOperations.add(UserRelationConstants.FOLLOW_LIST+user.getId(),String.valueOf(dto.getAuthorApUserId()),System.currentTimeMillis());
            zSetOperations.add(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId(),String.valueOf(user.getId()),System.currentTimeMillis());
        }else{
            //如果是1 取关该作者 zrem 集合添加数据
            zSetOperations.remove(UserRelationConstants.FOLLOW_LIST+user.getId(),String.valueOf(dto.getAuthorApUserId()));
            zSetOperations.remove(UserRelationConstants.FANS_LIST+dto.getAuthorApUserId(),String.valueOf(user.getId()));
        }
        return ResponseResult.okResult();
    }

}
